package com.inmarry.action;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.util.Random;

public final class VerifyCode extends Action {

    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse res ) throws Exception {
        HttpSession session = req.getSession(true);

        res.setContentType("image/jpeg;charset=utf-8");
        

        StringBuffer verifyCode  = new StringBuffer();
        Random random = new Random();
        for(int i=0; i<6; i++ ) {
            int  key = random.nextInt(62);

            verifyCode.append(code[key]);
        }

        String currentCode = verifyCode.toString();
        session.setAttribute("verifycode", currentCode);

        BufferedImage image = new BufferedImage(60, 20,
                BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        
        g.setColor(Color.decode("#000000"));
        g.fillRect(0, 0, 60, 20);
        g.setColor(Color.decode("#FFFFFF"));
        g.drawString(currentCode, 3, 15);
        g.dispose();

        OutputStream toClient = res.getOutputStream();
        ImageIO.write(image, "JPEG", toClient);
        toClient.close();

        //返回一个空的ActionForward
        return null;
    }


    private String[] code = {
        "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
        "q", "r", "s", "t", "w", "v", "u", "x", "y", "z",
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
        "Q", "R", "S", "T", "W", "V", "U", "X", "Y", "Z"
    };

}

